<?php

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;

/**
 * API基础控制器
 */
abstract class BaseApiController extends BaseController
{
    /**
     * 成功响应
     */
    protected function success($data = null, $msg = 'success', $code = 200)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'timestamp' => time()
        ]);
    }
    
    /**
     * 错误响应
     */
    protected function error($msg = 'error', $code = 400, $data = null)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'timestamp' => time()
        ], $code);
    }
    
    /**
     * 获取请求参数
     */
    protected function getParams($rules = [], $message = [])
    {
        $params = $this->request->param();
        
        if (!empty($rules)) {
            $this->validate($params, $rules, $message);
        }
        
        return $params;
    }
    
    /**
     * 获取分页参数
     */
    protected function getPageParams()
    {
        return [
            'page' => (int)$this->request->param('page', 1),
            'limit' => (int)$this->request->param('limit', 10)
        ];
    }
    
    /**
     * 分页响应
     */
    protected function pageSuccess($list, $total, $page = 1, $limit = 10, $msg = 'success')
    {
        return $this->success([
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit)
        ], $msg);
    }
}
